package com.example.demo.service.impl;

import com.example.demo.myannotation.CustomCacheEvict;
import com.example.demo.myannotation.CustomCachePut;
import com.example.demo.myannotation.CustomCacheable;
import com.example.demo.pojo.Person;
import com.example.demo.service.HelloService;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

@Service
public class HelloServiceImpl implements HelloService {

    private final Map<String,Person> map=new HashMap<>();

    @Override
    @CustomCacheable(value = "custom",key = "#id")
    public Person getById(Integer id) {
        System.out.println("查询数据：getById");

        if (map.containsKey(id.toString())){
            return map.get(id.toString());
        }

        return new Person();
    }

    @Override
    @CustomCacheable(value = "custom",key = "#person.id")
    public Person getByPerson(Person person) {
        System.out.println("查询数据：getByPerson");
        if (!map.containsKey(person.getId().toString())){
            return new Person();
        }

        return map.get(person.getId().toString());
    }

    @Override
    @CustomCachePut(value = "custom",key = "#id")
    public Person put(Integer id, String name, Integer age) {
        System.out.println("插入数据：id、name、age");
        Person person=new Person();
        person.setId(id);
        person.setName(name);
        person.setAge(age);

        map.put(id.toString(),person);

        return person;
    }

    @Override
    @CustomCachePut(value = "custom",key = "#person.id")
    public Person put2(Person person) {
        System.out.println("插入数据：person");
        map.put(person.getId().toString(),person);

        return person;
    }

    @Override
    @CustomCacheEvict(value = "custom",key = "#id")
    public Person deleteById(Integer id) {
        System.out.println("删除数据：deleteById");

        Person person=map.get(id.toString());
        map.remove(id.toString());

        return person;
    }

    @Override
    @CustomCacheEvict(value = "custom",key = "#result.id")
    public Person delete2(Person person) {
        System.out.println("删除数据：person");
        map.remove(person.getId().toString());

        return person;
    }
}
